//
//  IndexViewController.m
//  e家园设计
//
//  Created by lanou on 15/4/13.
//  Copyright (c) 2015年 lanou3g.com. All rights reserved.
//


#import "IndexViewController.h"
#import "CustomTableViewCell.h"
#import "lunboTableViewCell.h"
#import "Index_detailViewController.h"

#define URLStr @"http://ihome.cmfmobile.com:8080/sp/custom/getIndexProjectList.do"
#define ACTURLStr @"http://ihome.cmfmobile.com:8080/sp/custom/getGoodActivity.do?pn=1"
@interface IndexViewController ()<UIScrollViewDelegate,UITableViewDataSource, UITableViewDelegate, MyConnectionDelegate, PullDelegate>
{
    UITableView *_tableView;
}
@property (nonatomic, retain)UIScrollView *scroll;
@property (nonatomic, retain)UIPageControl *pageControl;
@property (nonatomic, retain)NSMutableArray *tableArray;
@property (nonatomic, retain)NSMutableDictionary *urlDic;
@property (nonatomic, retain)NSMutableDictionary *actUrlDic;
@property (nonatomic, retain)NSMutableArray *actArray;
@end

@implementation IndexViewController
- (void)dealloc
{
    [_scroll release];
    [_pageControl release];
    [_tableArray release];
    [_actUrlDic release];
    [_actArray release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.tableArray = [NSMutableArray array];
        self.urlDic = [NSMutableDictionary dictionary];
        [self.urlDic setObject:@"1" forKey:@"pn"];
        self.actUrlDic = [NSMutableDictionary dictionary];
        [self.actUrlDic setObject:@"1" forKey:@"pn"];
        self.actArray = [NSMutableArray array];
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"精品欣赏";


    
    [self createTableView];
    [self refresh];
    
}
#pragma mark -
#pragma mark 下拉刷新,上拉加载

- (void)scrollView:(UIScrollView *)scrollView loadWithState:(LoadState)state
{
    if (state == PullDownLoadState) {
        [self performSelector:@selector(refresh) withObject:nil afterDelay:0];
    }else{
        [self performSelector:@selector(downLoad) withObject:nil afterDelay:0];
    }
}

- (void)refresh
{
    [self.urlDic setObject:@"1" forKey:@"pn"];
    [self.tableArray removeAllObjects];
    [self.actUrlDic setObject:@"1" forKey:@"pn"];
    [self.actArray removeAllObjects];
    [self startConnectionWithType:PullDownLoadState];
}

- (void)downLoad
{
    NSString *str = self.urlDic[@"pn"];
    int num = [str intValue];
    num++;
    NSString *page = [NSString stringWithFormat:@"%d", num];
    [self.urlDic setObject:page forKey:@"pn"];
    [self startConnectionWithType:PullUpLoadState];
}

#pragma mark -
#pragma mark 网络请求

- (void)receiveDataFinished:(NSData *)data type:(NSInteger)type
{
    
    if (type == 3) {
        NSError *error = nil;
        NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        if (error) {
            NSLog(@"error");
        }
        [self.actArray addObjectsFromArray:array];
    }else
    {
        NSError *error = nil;
        NSMutableArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        if (error) {
            NSLog(@"%@", error);
        }
        
        for (int i = 0; i < array.count; i++) {
            NSDictionary *dic = array[i];
            NSArray *arr = dic[@"imageUrl"];
            if (arr.count == 1) {
                [array removeObjectAtIndex:i];
            }
        }
        [self.tableArray addObjectsFromArray:array];
        [_tableView reloadData];
        [_tableView stopLoadWithState:(LoadState)type];
    }
    if (self.tableArray.count > self.actArray.count) {
        [self startActConnection];
        NSString *str = self.actUrlDic[@"pn"];
        int num = [str intValue];
        num++;
        NSString *page = [NSString stringWithFormat:@"%d", num];
        [self.actUrlDic setObject:page forKey:@"pn"];
    }
    
}


- (void)startConnectionWithType:(NSInteger)type
{
    [MyConnection connectWithUrl:URLStr parmaters:self.urlDic delegate:self type:type];
}

- (void)startActConnection
{
    [MyConnection connectWithUrl:ACTURLStr parmaters:self.actUrlDic delegate:self type:3];
}
#pragma mark -
#pragma mark TableView

- (void)createTableView
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 44 - 49) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    [_tableView release];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    
    // 刷新
    _tableView.pullDelegate = self;
    _tableView.canPullDown = YES;
    _tableView.canPullUp = YES;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 280;
    }else
    {
        return 250;
    }
    
}

// tableView协议方法

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else
    {
        return self.tableArray.count;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        static NSString *cellIdentify = @"identify";
        lunboTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
        if (!cell) {
            cell = [[lunboTableViewCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier:cellIdentify];
        }
        [self createLunbo];
        [cell.lunboView addSubview:self.scroll];
        [self.scroll release];
        [cell.lunboView addSubview:self.pageControl];
        [self.pageControl release];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
        
    }else
    {
    static NSString *cellidentify = @"cellIdentify";
    CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellidentify];
        if (!cell) {
            cell = [[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellidentify];
        }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSDictionary *dic = self.tableArray[indexPath.row];
    NSArray *array = dic[@"imageUrl"];
    NSURL *url = [NSURL URLWithString:array[0]];
    [cell.image sd_setImageWithURL:url];
    cell.titleLable.text = dic[@"name"];
        NSString *style = [NSString stringWithFormat:@"%@|%@", dic[@"style"], dic[@"space"]];
    cell.styleLable.text = style;
    return cell;
    }
}

// cell的点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 1) {
        Index_detailViewController *detail = [[Index_detailViewController alloc] init];
        detail.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:detail animated:YES];
        [detail release];
        detail.dic = self.tableArray[indexPath.row];
        detail.actDic = self.actArray[indexPath.row];
    }
    
}




#pragma mark -
#pragma mark 轮播图

- (void)createLunbo
{
    self.scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200)];
    self.scroll.pagingEnabled = YES;
    self.scroll.contentSize = CGSizeMake(5 * self.scroll.frame.size.width, 0);
    
    self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, self.scroll.frame.size.height - 30, self.scroll.frame.size.width, 30)];
    self.pageControl.numberOfPages = 5;
    for (int i = 1; i <= 5; i++) {
        NSString *name = [NSString stringWithFormat:@"%d", i];
        NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"jpg"];
        UIImage *image = [UIImage imageWithContentsOfFile:path];
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake((i - 1) * self.scroll.frame.size.width, 0, self.scroll.frame.size.width, self.scroll.frame.size.height)];
        [imageView setImage:image];
        [self.scroll addSubview:imageView];
        [imageView release];
    }
    
    [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(autoChange) userInfo:nil repeats:YES];
    
    
    [self.pageControl addTarget:self action:@selector(clickOn:) forControlEvents:UIControlEventValueChanged];
    
}
- (void)autoChange
{
    NSInteger currentPage = self.pageControl.currentPage;
    NSInteger nextPage = currentPage + 1;
    if (nextPage == 5) {
        nextPage = 0;
    }
    self.pageControl.currentPage = nextPage;
    NSInteger num = nextPage;
    CGPoint a = self.scroll.contentOffset;
    a.x = num * self.scroll.frame.size.width;
    self.scroll.contentOffset = a;
}


- (void)clickOn:(id)sender
{
    UIPageControl *page = (UIPageControl *)sender;
    NSInteger num = page.currentPage;
    CGPoint a = self.scroll.contentOffset;
    a.x = num * self.scroll.frame.size.width;
    self.scroll.contentOffset = a;
}

// 协议方法

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView == self.scroll) {
        NSInteger num = scrollView.contentOffset.x / scrollView.frame.size.width;
        self.pageControl.currentPage = num;
    }
}







- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
